package com.jsnj33.pdaproject.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jsnj33.pdaproject.R;
import com.jsnj33.pdaproject.adapter.FormHorizontalAdapter;
import com.jsnj33.pdaproject.adapter.JobAdapter;
import com.jsnj33.pdaproject.base.BaseActivity;
import com.jsnj33.pdaproject.bean.JobBean;
import com.jsnj33.pdaproject.bean.MainBean;
import com.jsnj33.pdaproject.bean.MsgBean;
import com.jsnj33.pdaproject.bean.ReasonBean;
import com.jsnj33.pdaproject.constant.Constants;
import com.jsnj33.pdaproject.utils.SaNetUtils;
import com.jsnj33.pdaproject.utils.StringUtility;
import com.jsnj33.pdaproject.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpClient;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;


public class JobReportActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "JobReportActivity";
    private final static String SCAN_ACTION = ScanManager.ACTION_DECODE;//default action

    private Vibrator mVibrator;
    private ScanManager mScanManager;
    private SoundPool soundpool = null;
    private int soundid;
    private boolean isScaning = false;
    private Button btnRetryScan;
    private TextView title;
    private RelativeLayout rProgressBar;
    private TextView tv_gh_no;
    private AlertDialog dialog;
    private JobAdapter adapter;

    private List<JobBean> list = new ArrayList<>();
    private List<MainBean> listAdress;
    private String tailUrl;
    private EditText etDep;
    private String dep = "";
    private EditText et_Reason;
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            isScaning = false;
            soundpool.play(soundid, 1, 1, 0, 0, 1);
            mVibrator.vibrate(100);

            byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
            int barcodelen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
            byte temp = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);
            Log.i(TAG, "onReceive: " + temp);
            String str = new String(barcode, 0, barcodelen);

            Log.i(TAG, "onReceive: " + str);
            if (StringUtility.isEmpty(str)) {
                ToastUtil.showGravityToast(JobReportActivity.this, "扫码失败！", Gravity.CENTER, 0, 0);
                return;
            }
            String sbs = str.substring(0, 2);
            Log.i(TAG, "onReceive: " + sbs);
            Pattern p = Pattern.compile("[a-zA-z]");
            if (sbs.equals("TZ")) {
                /**
                 * 制令码
                 */
                setGoodsData(str);
                Log.i(TAG, "onReceive: ”制令码");
                return;
            } else if (!p.matcher(str).find()) {
                Log.i(TAG, "onReceive: 设备码");
                //设备码
                dep = str;
                if (etDep != null) {
                    etDep.setText(dep);
                }
                return;
            } else {
                /**
                 * 工号
                 */
                tv_gh_no.setText(str);
                Log.i(TAG, "onReceive: “工号");
                return;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_job_report);
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        btnRetryScan = findViewById(R.id.btnRetryScan);
        rProgressBar = findViewById(R.id.rProgressBar);
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initScan();
        IntentFilter filter = new IntentFilter();
        int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
        String[] value_buf = mScanManager.getParameterString(idbuf);
        if (value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
            filter.addAction(value_buf[0]);
        } else {
            filter.addAction(SCAN_ACTION);
        }

        registerReceiver(mScanReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mScanManager != null) {
            mScanManager.stopDecode();
            isScaning = false;
        }
        unregisterReceiver(mScanReceiver);
    }

    private void initScan() {
        mScanManager = new ScanManager();
        mScanManager.openScanner();

        mScanManager.switchOutputMode(0);
        soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
        soundid = soundpool.load("/etc/Scan_new.ogg", 1);
    }

    private void initData() {
        title = findViewById(R.id.title);
        tv_gh_no = findViewById(R.id.tv_gh_no);
        RecyclerView rvHorizontal = findViewById(R.id.recyclerview_horizontal);
        RecyclerView rvVertical = (RecyclerView) findViewById(R.id.recyclerview_vertical);
        Button submit = (Button) findViewById(R.id.submit);

        submit.setOnClickListener(this);

        Intent intent = getIntent();
        if (intent != null) {
            title.setText(getIntent().getStringExtra("title"));
            listAdress = (List<MainBean>) getIntent().getSerializableExtra("list");
            tailUrl = listAdress.get(0).getAddress();
        }
        rvHorizontal.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        FormHorizontalAdapter adapterHorizontal = new FormHorizontalAdapter(this) {
            @Override
            protected void itemChick(String address) {
                tailUrl = address;
            }
        };
        rvHorizontal.setAdapter(adapterHorizontal);
        adapterHorizontal.setList(listAdress);


        initRecyclerView(rvVertical, LinearLayoutManager.VERTICAL);
        btnRetryScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeInfo();
            }
        });
    }

    private void initRecyclerView(RecyclerView recyclerView, int vertical) {
        recyclerView.setLayoutManager(new LinearLayoutManager(this, vertical, false));
        adapter = new JobAdapter(this);
        recyclerView.setAdapter(adapter);
    }

    private void fillInData(final int position, final JobBean jobBean) {
        if (dialog != null && dialog.isShowing()) {
            return;
        }
        final AlertDialog.Builder builder = new AlertDialog.Builder(JobReportActivity.this);
        View view = LayoutInflater.from(JobReportActivity.this).inflate(R.layout.pop_job_view, null);
        builder.setView(view);
        //这个位置十分重要，只有位于这个位置逻辑才是正确的
        dialog = builder.show();
        dialog.setTitle("请输入:");
        final EditText etNumber = view.findViewById(R.id.et_number);
        final EditText etYqty = view.findViewById(R.id.et_yqty);
        final TextView et_Ynum = view.findViewById(R.id.et_Ynum);
        et_Ynum.setText(jobBean.getQty()+"");
        etDep = view.findViewById(R.id.et_dep);
        etDep.setText(dep);
        et_Reason = view.findViewById(R.id.et_Reason);
        view.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    if (position >= 0) {
                        String number = etNumber.getText().toString();
                        if (!StringUtility.isEmpty(number)) {
                            list.get(position).setSmqty(Double.parseDouble(number));
                        }
                        if (TextUtils.isEmpty(etDep.getText().toString())) {
                            list.get(position).setDep("0");
                        } else {
                            list.get(position).setDep(etDep.getText().toString());
                        }
                        list.get(position).setRem(et_Reason.getText().toString());
                        if (TextUtils.isEmpty(etYqty.getText().toString())) {
                            list.get(position).setYqty(Double.parseDouble("0"));
                        } else {
                            list.get(position).setYqty(Double.parseDouble(etYqty.getText().toString()));
                        }

                    } else {
                        String number = etNumber.getText().toString();
                        if (!StringUtility.isEmpty(number)) {
                            jobBean.setSmqty(Double.parseDouble(number));
                        }
                        jobBean.setRem(et_Reason.getText().toString());
                        if (TextUtils.isEmpty(etDep.getText().toString())) {
                            jobBean.setDep("0");
                        } else {
                            jobBean.setDep(etDep.getText().toString());
                        }
                        if (TextUtils.isEmpty(etYqty.getText().toString())) {
                            jobBean.setYqty(Double.parseDouble("0"));
                        } else {
                            jobBean.setYqty(Double.parseDouble(etYqty.getText().toString()));
                        }
                        list.add(jobBean);
                    }
                    adapter.setList(list);
                    Log.d(TAG, "onClick: " + new Gson().toJson(list));
                    btnRetryScan.setVisibility(View.VISIBLE);
                } catch (Exception e) {
                    ToastUtil.showLongToast(JobReportActivity.this, e.getMessage() + "");
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.submit:
                submitData();
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    /**
     * prd_no:扫到的货品码
     * mo_no:制令单号
     * qty:实缴数
     * user：作业人员
     * wh:仓库
     */
    private void submitData() {
        String user = tv_gh_no.getText().toString();
        if (StringUtility.isEmpty(user)) {
            ToastUtil.showGravityToast(this, "请扫描您的工号！", Gravity.CENTER, 0, 0);
            return;
        }
        rProgressBar.setVisibility(View.VISIBLE);
        Map<String, Object> map = new HashMap<>();
        map.put("table", listAdress.get(0).getCodeName());
        map.put("tablename", title.getText().toString());
        map.put("usr", user);
        map.put("list", adapter.getData());
        String url = Constants.SUBMIT_GZ_JOB;
        getHttpData(url, map);
    }

    private void getHttpData(final String url, Map<String, Object> map) {
        RequestParams requestParams = new RequestParams(url);
        String gson = new Gson().toJson(map);
        requestParams.setBodyContent(gson);
        requestParams.setAsJsonContent(true);
        x.http().post(requestParams, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                rProgressBar.setVisibility(View.GONE);
                try {
                    Log.d(TAG, "getHttpData-onSuccess: " + jsonObject.toString());
                    int errCode = jsonObject.getInt("errCode");
                    String msg = jsonObject.getString("errMsg");
                    if (errCode == -1) {
                        ToastUtil.showLongGravityToast(JobReportActivity.this, msg, Gravity.CENTER, 0, 0);
                    } else {
                        //请求成功
                        removeInfo();
                        ToastUtil.showToast(JobReportActivity.this, "提交成功");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i(TAG, "Exception: " + e.getMessage());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
//                ToastUtil.showLongToast(JobReportActivity.this, "网络异常");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                rProgressBar.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 扫描制令单号
     *
     * @param osNo
     */
    private void setGoodsData(final String osNo) {
        AsyncHttpClient client = SaNetUtils.getAsyncHttpClient();
        String url = Constants.SCANNING_PRODUCT_CODE + tailUrl;
        Log.i(TAG, "setGoodsData: " + url);
        RequestParams requestParams = new RequestParams(url);
        final JSONObject map = new JSONObject();
        try {
            map.put("os_no", osNo);
            map.put("rem", "0");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        requestParams.setBodyContent(map.toString());
        x.http().post(requestParams, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                String str = new String(response.toString());
                Log.i(TAG, "setGoodsData=onSuccess: " + response.toString());
                try {
                    JobBean beans = new Gson().fromJson(str, JobBean.class);
                    try {
                        if (beans.getErrCode().equals("-1")) {
                            ToastUtil.showLongGravityToast(JobReportActivity.this, beans.getErrMsg(), Gravity.CENTER, 0, 0);
                            return;
                        }
                    } catch (Exception e) {

                    }
                    beans.setOs_no(osNo);
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            JobBean jobBean = list.get(i);
                            if (jobBean.getOs_no().equals(beans.getOs_no())) {
                                fillInData(i, jobBean);
                                return;
                            }
                        }
                    }
                    fillInData(-1, beans);
                    quearTypeList("" + response.optString("zc_no"));
                } catch (Exception e) {
                    Log.i(TAG, "setGoodsData:-ExceptionL: " + e.getMessage());

                    try {
                        List<MsgBean> msgBean = new Gson().fromJson(str, new TypeToken<List<MsgBean>>() {
                        }.getType());
                        MsgBean bean = msgBean.get(0);
                        int errCode = bean.getErrCode();
                        String msg = bean.getErrMsg();
                        if (errCode == -1) {
                            ToastUtil.showLongGravityToast(JobReportActivity.this, msg, Gravity.CENTER, 0, 0);
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d(TAG, "onError: " + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }

    /**
     * 获取不合格原因列表
     *
     * @param zcNo
     */
    private void quearTypeList(final String zcNo) {
        RequestParams requestParams = new RequestParams(Constants.QUEARLIST + zcNo);
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d(TAG, "onSuccess: " + result.toString());
                TypeToken<List<ReasonBean>> typeToken = new TypeToken<List<ReasonBean>>() {
                };
                ArrayList<ReasonBean> reasonList = new Gson().fromJson(result, typeToken.getType());
                reasonList.add(0, new ReasonBean("全部合格"));
                adapter.setReasonList(reasonList);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d(TAG, "Throwable: " + ex.getMessage());

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 提交数据后清空数据
     */
    private void removeInfo() {
//        list = new ArrayList<>();
//        adapter.setList(list);
        tv_gh_no.setText("");
        dep = "";
        if (list != null) {
            list.clear();
        }
        adapter.clear();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeInfo();
    }
}

